package org.example.admin.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.UUID;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.example.admin.constant.RedisConstants;
import org.example.admin.vo.CaptchaVo;
import org.example.core.utils.R;
import org.example.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 小杰_cc
 * @version 1.0
 */

@RestController
@RequestMapping("/sys/backend")
public class KaptchaController {

    @Autowired
    private Producer producer;

    @Autowired
    private RedisService redisService;

    @GetMapping("/captchaImg")
    public R<CaptchaVo> getCaptchaImg() throws IOException {
        // 生成验证码信息
        String capText = producer.createText();

        // 保存到redis中
        String captchaKey = UUID.randomUUID().toString(true);   // 验证码标识
        redisService.setObject(RedisConstants.CAPTCHA_KEY + captchaKey, capText, 5L, TimeUnit.MINUTES); // 有效期5分钟

        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setCaptchaKey(captchaKey);

        // 设置成图片,转成base64形式
        String base64Img;
        BufferedImage image = producer.createImage(capText);
        try(ByteArrayOutputStream out = new ByteArrayOutputStream()){
            ImageIO.write(image,"jpg",out);
            String str  = "data:image/jpeg;base64,";
            base64Img = str + Base64Encoder.encode(out.toByteArray()).replace("\n","").replace("\r","");
            out.flush();
        }
        captchaVo.setBase64Img(base64Img);

        return R.ok(captchaVo);
    }
}
